import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useState, useEffect } from 'react';
import { Form, Input, Button, message } from 'antd';
import { MobileOutlined } from '@ant-design/icons';
import Cookies from 'js-cookie';
import logImg from '@/public/logo/white.gif';
// css
import styles from '@/styles/Login.module.scss';
// 组件
import Spin from '@/components/Spin';
// api
import { getVerifyCode, verifyCode } from '@/api/auth';

let timer = null,
    login_status = false;
const phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;

// 登录底部导航栏
const Nav = () => {
    return (
        <nav className={styles['nav']}>
            <Link href="/"><a>首页</a></Link>
            <span className={styles['sep']}>|</span>
            <Link href="/ticket" prefetch={false}><a>景区门票</a></Link>
            <span className={styles['sep']}>|</span>
            <Link href="/hotel" prefetch={false}><a>酒店住宿</a></Link>
            <span className={styles['sep']}>|</span>
            <Link href="/guide" prefetch={false}><a>旅游攻略</a></Link>
            <span className={styles['sep']}>|</span>
            <Link href="/about_us" prefetch={false}><a>公司简介</a></Link>
            <p>Copyright &copy;2001-{new Date().getFullYear()}&nbsp;西藏旅游股份有限公司 TibTour.com&nbsp;版权所有</p>
            <p><a href="https://beian.miit.gov.cn/" target="_blank" rel="noreferrer nofollow">藏ICP备13000028号-3</a></p>
        </nav>
    )
}

// 登录页
const Login = () => {

    const router = useRouter();
    const [form] = Form.useForm();
    const [phone, setPhone] = useState('');
    const [count, setCount] = useState(0);
    const [loading, setLoading] = useState(false);

    // 倒计时
    useEffect(() => {
        if (count === 0) {
            clearInterval(timer);
            return false
        }
        if (count === 59) {
            timer = setInterval(() => {
                setCount(count => count-1)
            }, 1000)
        }
    }, [count]);

    // 组件卸载时清除计时器
    useEffect(() => {
        return () => {
            clearInterval(timer)
        }
    }, []);

    // 获取验证码
    const getCode = () => {
        setCount(59);
        getVerifyCode(phone).then(res => {
            if(res.code === 0){
                message.success('验证码已发送');
            }
        })
    }

    // 提交登录
    const onLogin = ({ phone, code }) => {
        if(login_status) {
            return false
        }
        setLoading(true);
        login_status = true;
        verifyCode({
            purpose: "login",
            phone: phone,
            smsCode: code
        }).then(res => {
            login_status = false;
            setLoading(false);
            const { code, data } = res;
            if(code !== 0){
                return false
            }
            Cookies.set('token', data.token, { expires: 7 });
            Cookies.set('userInfo', JSON.stringify(data), { expires: 7 });
            const { redirect } = router.query;
            router.push(redirect ? redirect : '/')
        })
    };

    return (
        <div className={styles['login-page']}>
            <Spin loading={loading} />
            <div className={styles['bg']}></div>
            <div className={styles['main']}>
                <div className={styles['login-form']}>
                    <Link href="/">
                        <a className={styles['logo-link']}>
                            <img src={process.env.basePath + logImg.src} alt="" />
                        </a>
                    </Link>
                    <h3 className={styles['title']}>手机动态密码登录/注册</h3>
                    <Form className={styles['form']} form={form} onFinish={onLogin} autoComplete="off">
                        <Form.Item
                            name="phone"
                            rules={[
                                { required: true, message: '请输入手机号' },
                                {
                                    required: false, //在用户输入了内容后，再进行此项验证，所以要设为false
                                    pattern: phoneReg,
                                    message: '请填写正确的手机号'
                                }
                            ]}
                        >
                            <Input
                                className={styles['phone']}
                                placeholder="手机号"
                                value={phone}
                                onChange={(e) => { setPhone(e.target.value) }}
                            />
                        </Form.Item>
                        <Form.Item
                            className={styles['merge']}
                            name="code"
                            rules={[
                                { required: true, message: '请输入短信验证码' },
                                {
                                    required: false,
                                    pattern: new RegExp(/^[0-9]{6}$/, "g"),
                                    message: '请填写正确的短信验证码'
                                }
                            ]}
                        >
                            <Input className={styles['code']} placeholder="短信验证码" />
                        </Form.Item>
                        <Form.Item className={styles['merge']}>
                            <Button
                                className={styles['code-btn']}
                                icon={<MobileOutlined style={{ fontSize: '20px' }} />}
                                onClick={() => { getCode() } }
                                disabled={ (!count && !phoneReg.test(phone)) || !!count }
                            >{count ? `${count}s后重新发送` : '发送短信验证码'}</Button>
                        </Form.Item>
                        <Form.Item>
                            <Button className={styles['btn']} type="primary" htmlType="submit">登录/注册</Button>
                        </Form.Item>
                    </Form>
                    <Nav />
                </div>
            </div>
        </div>
    )
}
export default Login